#include "stdafx.h"
#include "EventDemultiplex.h"

namespace Network {
	fd_set EventDemultiplex::Selects (fd_set listeners)
	{
		fd_set returnSet;
		fd_set temp;

		returnSet.fd_count = 0;
		temp.fd_count = 1; //1 reserved for the temporary use

		//empty fd_set arrays
		for (int i = 0 ; i < FD_SETSIZE; ++i)	{
			returnSet.fd_array[i] = NULL;
			temp.fd_array[i] = NULL;
		}

		int count  = 0 ;
		for (u_int i = 0 ; i < listeners.fd_count; ++i) {
			temp.fd_array[0] = listeners.fd_array[i];

			// Winsock select
			// Select on listen(), accept(), connect(), connect() fail
			timeval timeout = {0,100}; //initialize to 0s, 100ms
			int number_of_handles = select(0, &temp, &temp, &temp, &timeout);

			if (number_of_handles > 0) {
				//Success; Add the descriptor to the end of array
				returnSet.fd_array[returnSet.fd_count] = listeners.fd_array[i];
				returnSet.fd_count++;
			} else if (number_of_handles == 0) {
				//fprintf(stdout, "Timeout on select()\n");
			} else if (number_of_handles == SOCKET_ERROR){
				int error = WSAGetLastError();
				//fprintf(stdout, "Socket error. WSA error code = %d\n", error);
			}
		}
		return returnSet;
	}
}